package com.woniuxy.commons.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.model.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
public class LoginErrorHandler implements AuthenticationFailureHandler {

    private ObjectMapper om = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json;charset=utf8");

        Result result = Result.fail(500,"用户名或密码错误");
        String json = om.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }

}
